<?php
/**
 * User: b179a9
 * Date: 12.09.11
 * Time: 17:48
 */

namespace Managers;

class Answers extends BaseManager
{
    const TABLE = '\Catalog\UserAnswers';
    protected $__table = self::TABLE;

    function recordExists($user_id, $map_id)
    {
        $entity = $this->_em->getRepository($this->__table)->findOneBy(array('user' => $user_id,
                                                                            'map' => $map_id));

        return $entity;
    }
    function  isAnswer($user_id, $map_id)
    {
         $qb = $this->_em->createQueryBuilder()
                ->select('a')
                ->from(self::TABLE, 'a');

         if(isset($user_id)) {
                    $qb->andWhere('a.user = :user')
                        ->setParameter('user', $user_id);
                }

         if(isset($map_id)) {
            $qb->andWhere('a.map = :map')
                ->setParameter('map', $map_id);
        }

        $res = $qb->getQuery()
                ->getArrayResult();

        return $res;
    }

    function add($user_id, $map_id, $user_answer, $correct_answer)
    {
        $order = $this->_em->getRepository(Orders::TABLE)->findOneBy(array('map' => $map_id, 'user' => $user_id));
        
        $answer = new \Catalog\UserAnswers();
        $user = $this->_em->getReference('\Catalog\Users', $user_id);
        $map = $this->_em->getReference('\Catalog\Maps', $map_id);
        $answer->setMap($map);
        $answer->setUser($user);
        $answer->setAnswer($user_answer);
        $isCorrect = strcasecmp(trim($user_answer), trim($correct_answer)) == 0;
        $answer->setIsCorrect($isCorrect);
        $now = new \DateTime();
        $answer->setTime($now);
        $answer->setWinner(false);

        $interval = $now->diff($order->getDate());
        $answer->setTimeTaken($now->getTimestamp() - $order->getDate()->getTimestamp());

        $this->_em->persist($answer);
        $this->_em->flush();
        return $answer;
    }

    public function getList($filters = array())
    {
        $qb = $this->_em->createQueryBuilder()
                ->select('ua', 'u', 'm')
                ->from(self::TABLE, 'ua')
                ->join('ua.user', 'u')
                ->join('ua.map', 'm');

        if (array_key_exists('correct', $filters) && !empty($filters['correct'])) {
            $qb->andWhere('ua.isCorrect = :correct')
                    ->setParameter('correct', $filters['correct']);
        }

        if (array_key_exists('map', $filters) && !empty($filters['map'])) {
            $qb->andWhere('ua.map = :map')
                    ->setParameter('map', $filters['map']);
        }

        if(array_key_exists('user', $filters)) {
            $qb->andWhere('u.id = :user')
                ->setParameter('user', $filters['user']);
        }

        $qb->orderBy('ua.winner', 'DESC')
                ->addOrderBy('ua.isCorrect', 'DESC')
                ->addOrderBy('ua.timeTaken', 'ASC');

        $res = $qb->getQuery()
                ->getArrayResult();
        return $res;
    }

    public function getTotal($map_id = null) {
        $qb = $this->_em->createQueryBuilder()
                ->select('count(a.id) as total')
                ->from(self::TABLE, 'a');

        if(isset($map_id)) {
            $qb->andWhere('a.map = :map')
                ->setParameter('map', $map_id);
        }

        $res = $qb->getQuery()
                ->getArrayResult();

        return $res[0]['total'];

    }

    public function addPhoto($answerId, $file)
    {

        $destination = dirname(APPLICATION_PATH) . '/public/upload/';

        if (!extension_loaded('imagick')) {
            throw new \Exception('Image magick is not installed');
        }

        $answer = $this->_em->find(self::TABLE, $answerId);

        if (!$answer) {
            throw new \Exception('Answer does not exist.');
        }

        if (!is_writeable($destination)) {
            throw new \Exception("{$destination} is not writable.");
        }

        if ($file['size'] == 0) {
            throw new \Exception('Invalid file size.');
        }

        $resultName = $file['name'];
        $adding = 'a';
        $tmpName = $resultName;
        while (file_exists($destination . $tmpName)) {
            $tmpName = pathinfo($resultName, PATHINFO_FILENAME) . $adding . '.' . pathinfo($resultName, PATHINFO_EXTENSION);
            $adding++;
        }
        $resultName = $tmpName;

        if (!move_uploaded_file($file['tmp_name'], $destination . $resultName)) {
            throw new \Exception("Couldn't move the file: {$file['tmp_name']}.");
        }

        $resultUrl = '/upload/' . $resultName;
        $answer->setImg($resultUrl);

        $this->_em->persist($answer);
        $this->_em->flush();
        return $answer;

    }

    public function setWinner($id, $winner = true)
    {
        $answer = $this->_em->find(self::TABLE, $id);

        if (!$answer) {
            throw new \Exception('Answer does not exist.');
        }

        if ($answer->getWinner() == $winner) {
            throw new \Exception('Nothing to do.');
        }
        $answer->setWinner($winner);
        $this->_em->persist($answer);
        $this->_em->flush();
        return $answer;
    }
}
